<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class CodeHelper extends Model
{
    public $incrementing = false;
    protected $primaryKey = 'key';
    protected $guarded=[];

    public static function getIncrementValue($key, $default = 1)
    {
        $setting = null;
        DB::transaction(function () use ($key, $default, &$setting) {
            $setting = Setting::where('key', $key)
                ->lockForUpdate()
                ->first();
            if ($setting) {
//                $setting->increment('value');
                $setting->value++;
                $setting->save();
            } else {
                $setting = Setting::create(['key' => $key, 'value' => $default]);
            }
        });
        return $setting->value;
    }

    /**
     * @param String $key
     * @return mixed
     */
    public static function getValue(String $key)
    {
        $setting = Setting::find($key);
        return !$setting ? null : $setting->value;
    }

    /**
     * @param string $key
     * @param $value
     */
    public static function setValue(String $key, $value)
    {
        return Setting::updateOrCreate([
            'key' => $key,
        ], [
            'value' => $value
        ]);
    }
}
